/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import fs from 'fs';
import os from 'os';
import path from 'path';
import process from 'process';

import { HvigorCommonConst } from '../../common/options/common-const.js';
import { globalData } from '../../internal/data/global-data.js';
import { HvigorLogger } from '../../log/hvigor-log.js';

const configFileName = HvigorCommonConst.BUILD_PROFILE_FILE_NAME;
const propertiesAlias = 'prop';
const modeAlias = 'mode';

const _log: HvigorLogger = HvigorLogger.getLogger('hvigor-InitEnvConfigProps');

/**
 * 加载liftOff获取到的configFiles中的具体一个配置文件的路径
 *
 * @return {string} path 返回cwd的路径
 */
export function initEnvConfigProps(): void {
  const opts = globalData.cliOpts!;
  const env = globalData.cliEnv;

  // load 根项目下的build_profile
  const configFilePath: string = path.resolve(process.cwd(), HvigorCommonConst.BUILD_PROFILE_FILE);

  if (!fs.existsSync(configFilePath)) {
    _log.printErrorExit('CANNOT_FIND_PROJECT_BUILD_FILE', [HvigorCommonConst.BUILD_PROFILE_FILE, env.cwd]);
  }

  const properties = new Map<string, string>();

  if (opts.prop !== undefined) {
    [opts.prop].flat(2).forEach((value: string) => {
      const arr = value.split('=');
      properties.set(arr[0], arr[1]);
    });
  }

  env.configProps = new Map<string, string | Map<string, string> | undefined>([
    [configFileName, configFilePath],
    [propertiesAlias, properties],
    [modeAlias, opts.mode],
  ]);
}
